package com.yilin.tms.gps.service.impl;


import com.yilin.tms.core.components.repository.GpsDataRepository;
import org.springframework.data.domain.*;
import com.yilin.tms.core.entity.gps.GpsPoint;
import com.yilin.tms.gps.service.ITrailStorageService;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

/**
 * 轨迹存储服务
 *
 * @author liuxu :)
 * @version 1.0
 * @date 2022-10-28 0028
 */
@Service
@Transactional
public class TrailStorageService implements ITrailStorageService {

    @Resource
    GpsDataRepository gpsDataRepository;

    @Override
    public void addTrackPoints(List<GpsPoint> gpsPointList) {
        gpsDataRepository.saveAll(gpsPointList);
    }

    @Override
    public void removePoint(GpsPoint gpsPoint) {
        gpsDataRepository.deleteById(gpsPoint.get_id());
    }

    @Override
    public Page<GpsPoint> queryPointByTransportNo(GpsPoint gpsPoint, Integer start, Integer limit) {
        if (start == null) start = 1;
        if (limit == null) limit = 10;
        Pageable pageable = PageRequest.of(start - 1, limit);
        Example<GpsPoint> stExample = Example.of(gpsPoint);
        return gpsDataRepository.findAll(stExample, pageable);
    }

    @Override
    public long getCountDocuments(String transportNo, Date startDate, Date endDate) {
        return 0;
    }

    @Override
    public GpsPoint getRecentPointByTruckNo(String transportNo) {
        GpsPoint gpsPoint = new GpsPoint();
        gpsPoint.setTransportNo(transportNo);
        Example<GpsPoint> stExample = Example.of(gpsPoint);
        List<GpsPoint> all = gpsDataRepository.findAll(stExample);
        return all.size() > 0 ? all.get(0) : null;
    }

    /**
     * 查询运单轨迹
     */
    @Override
    public List<GpsPoint> getPointsBytransportNo(String transportNo) {
        GpsPoint gpsPoint = new GpsPoint();
        gpsPoint.setTransportNo(transportNo);
        Example<GpsPoint> stExample = Example.of(gpsPoint);
        return gpsDataRepository.findAll(stExample);
    }

    /**
     * 查询运单轨迹
     */
    @Override
    public List<GpsPoint> findAllPointsByDate(String traceId, String gpsTime) {
        return gpsDataRepository.findAllPointsByDate(traceId,gpsTime);
    }

    @Override
    public List<GpsPoint> findAllPointsByTraceId(String traceId, Integer page, Integer limit) {
        if (page == null) page = 1;
        if (limit == null) limit = 10;
        Pageable pageable = PageRequest.of(page - 1, limit);
        return gpsDataRepository.findAllPointsByTraceId(traceId,pageable);
    }
}
